package edu.tamu.cs.studio;

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	Gameboard game;
	AIengine ai;
	Context shc;
	private static final String TAG = GameView.class.getSimpleName();
	private static final boolean False = false;
	private GameThread thread;
	//private Piece piece;
	public GameView(Context context, AttributeSet attrs){super(context, attrs);}
	public GameView(Context context, AttributeSet attrs, int defStyle){super(context, attrs,defStyle);}
	SharedPreferences sharedPreferences;
	
	public GameView(Context context) 
	{
		super(context);
		shc=context;
		sharedPreferences =  shc.getSharedPreferences("larry",Context.MODE_PRIVATE);
		getHolder().addCallback(this);
		//piece = new Piece(100,100);//creates the original piece on the board
		game = new Gameboard();
		ai = new AIengine();
		thread = new GameThread(getHolder(),this);
		setFocusable(false);
		
		// TODO Auto-generated constructor stub
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
		// TODO Auto-generated method stub
		
	}

	public void surfaceCreated(SurfaceHolder holder) 
	{
		game.setup();
		thread.setRunning(true);
		thread.start();
		// TODO Auto-generated method stub
	}

	public void surfaceDestroyed(SurfaceHolder holder)
	{
		Log.d(TAG, "Surface is being destroyed");
		boolean retry = true;
		while(retry)
		{
			try
			{
				thread.join();
				retry = false;
			}
			catch(InterruptedException e){}
			
		}
		// TODO Auto-generated method stub
		Log.d(TAG, "Thread was shut down cleanly");
	}
	
	@Override	
	protected void onDraw(Canvas canvas)
	{
		Paint paint = new Paint();
		paint.setColor(Color.WHITE);
		String text = "x="+Integer.toString(this.getWidth());
		Bitmap scaledBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.gamescreen), 320, 480,true);
		//draws background
		canvas.drawBitmap(scaledBitmap,0,0,null);
		//draws the "x = "
		//canvas.drawText(text, 25, 25, paint);
		//piece.draw(canvas);
		game.showNextPos();
		board_coordinates(canvas);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{
		int ipip=0;
		if (event.getAction() == MotionEvent.ACTION_DOWN) 
		{
			// delegating event handling to the piece
			//if(event.getX() > 15 && event.getX() < 47 && event.getY() > 105 && event.getY() < 137)
			
			for(int i=1;i<9;i++)
			{
				for(int j=1;j<9;j++)
				{
					if(event.getX() > (15+((j-1)*37)) && event.getX() < (47+((j-1)*37)) && event.getY() > (105+((i-1)*37)) && event.getY() < (137+((i-1)*37)))
					{
						int player_color = shared_preferences_getint("color",0);
						char player,opponent;
						if(player_color==1)
						{
							player='@';
							opponent='O';
						}
						else
						{
							player='O';
							opponent='@';
						}
						if(game.currentColor()==player)	
						{
							game.move(i,j);
						
							game.showNextPos();
							ipip=game.count_num_moves();
						}
						if(game.currentColor()==opponent)	
						{
							ai.difficulty_of_the_AI('2', game);
							game.move((int)ai.row,(int)ai.column);
							game.showNextPos();
							ipip=ipip+game.count_num_moves();
							return true;
						}
					}
				}	
				
				//piece.setX(31);
				//piece.setY(121);
			
			}
			if(event.getX() > 33 && event.getX() < 133 && event.getY() > 416 && event.getY() < 458)
			{
				game.undo();
				game.showNextPos();
			}
			if(event.getX() > 188 && event.getX() < 288 && event.getY() > 416 && event.getY() < 458)
			{
				game.redo();
				game.showNextPos();
			}
			
			//System.out.println(event.getX() + ",y= " + event.getY());
			// check if in the lower part of the screen we exit
			//if (event.getY() > getHeight() - 50) 
			//{
				//thread.setRunning(false);
				//((Activity)getContext()).finish();
			//}
			if(game.checkgameover()||(ipip==0))
			{
				thread.setRunning(False);
			}
			
		} 
		if (event.getAction() == MotionEvent.ACTION_UP) 
		{
			// touch was released
			//if (piece.isTouched())
			{
			//	piece.setTouched(false);
			}
			return true;
		}
		return true;
	}
	
	
	public void board_coordinates(Canvas canvas)
	{
		
		
		Paint paint=new Paint();
		int height=37, width=37;
		int start_pointx=31,start_pointy=121;
		int x,y;
		char a,b;
		for(int i=1;i<9;i++)
		{
			for(int j=1;j<9;j++)
			{
				x=start_pointx+((j-1)*(width));
				y=start_pointy+((i-1)*(height));
				//board_coordinates( board[i][j],x,y,piece);Paint paint = new Paint();
				a=game.board[i][j];
				b=game.currentColor();
				if(a == '@')
				{
					paint.setColor(Color.BLACK);
					canvas.drawCircle(x, y,10, paint);
				}
				if(a == 'O')
				{
					paint.setColor(Color.WHITE);
					canvas.drawCircle(x, y,10, paint);
				}
				if(b == '@' && a == '*')
				{
					paint.setColor(Color.BLACK);
					canvas.drawCircle(x, y,5, paint);
				}
				if(b == 'O' && a == '*')
				{
					paint.setColor(Color.WHITE);
					canvas.drawCircle(x, y,5, paint);
				}
				a='d';
			}
		}
	}
	
	public int shared_preferences_getint(String key,int value)
    {
        int storedPreference = sharedPreferences.getInt(key, 0);
        return storedPreference;
    }
	
}

